package com.jamcodingnm.apps.abqevents.rss;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


/**
 * RSS Handler for ABQ Event data
 * 
 * @author Marcos
 *
 */
public class RSSHandler extends DefaultHandler {
	private final int RSS_TITLE = 1;
	private final int RSS_LINK = 2;
	private final int RSS_DESCRIPTION = 3;
	private final int RSS_CATEGORY = 4;
	private final int RSS_DATE = 5;
	private final int RSS_DETAIL = 6;
	private final int RSS_IMAGEURL = 7;

	private RSSFeed feed;
	private RSSItem item;

	@SuppressWarnings("unused")
	private int depth = 0;
	private int currentstate = 0;

	/**
	 * Handler constructor
	 */
	protected RSSHandler() {
	}

	/**
	 * @return RSSFeed
	 */
	protected RSSFeed getFeed() {
		return feed;
	}

	@Override
	public void startDocument() throws SAXException {
		feed = new RSSFeed();
		item = new RSSItem();
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {

		depth++;
		if (qName.equals("channel")) {
			currentstate = 0;
			return;
		} else if (qName.equals("image")) {
			currentstate = RSS_IMAGEURL;
			return;
		} else if (qName.equals("item")) {
			// create a new item
			item = new RSSItem();
			return;
		} else if (qName.equals("title")) {
			currentstate = RSS_TITLE;
			return;
		} else if (qName.equals("description")) {
			currentstate = RSS_DESCRIPTION;
			return;
		} else if (qName.equals("link")) {
			currentstate = RSS_LINK;
			return;
		} else if (qName.equals("category")) {
			currentstate = RSS_CATEGORY;
			return;
		} else if (qName.equals("dc:date")) {
			currentstate = RSS_DATE;
			return;
		} else if (qName.equals("dc:subject")) {
			currentstate = RSS_DETAIL;
			return;
		} else {
			currentstate = 0;
		}
	}

	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		depth--;

		if (qName.equals("item")) {
			feed.addItem(item);
			return;
		}
	}

	@Override
	public void characters(char ch[], int start, int length) {
		String theString = new String(ch, start, length);
		// Log.i("RSSReader", "characters[" + theString + "]");

		switch (currentstate) {
		case RSS_TITLE:
			item.setTitle(theString);
			currentstate = 0;
			break;
		case RSS_LINK:
			item.setLink(theString);
			currentstate = 0;
			break;
		case RSS_DESCRIPTION:
			item.setDescription(theString);
			currentstate = 0;
			break;
		case RSS_CATEGORY:
			item.setCategory(theString);
			currentstate = 0;
			break;
		case RSS_DATE:
			item.setStringDate(theString);
			currentstate = 0;
			break;
		case RSS_DETAIL:
			item.addDetail(theString);
			currentstate = 0;
			break;
		case RSS_IMAGEURL:
			item.setImageURL(theString);
			currentstate = 0;
			break;
		default:
			return;
		}
	}
}